<script setup lang="ts">

import { reactive, ref, watch } from 'vue';
import { MetaData } from '../../types/MetaData'
import { KeyValuePair } from '../../types/KeyValuePair';
import NtmKeyValuePairEditor from './NtmKeyValuePairEditor.vue';
import Errors from '../../types/Errors';

const model = defineModel<MetaData>({ default: {} as MetaData })
const errors = defineModel<Errors>('errors', { default: {} })
const props = defineProps<{showHeader?: boolean}>();
const { showHeader = true } = props;

const keyValuePairs = ref<KeyValuePair[]>(Object.keys(model.value).map(key => {
    return {
        key, value: model.value[key]
    }
}));

const addError = (all: Errors, key: string, error: string) => {
    all[key] = all[key] || []
    all[key].push(error);
}

watch(keyValuePairs, (values) => {
    const newErrors: Errors = {};
    const dict = values
        .filter(pair => pair.key && pair.key !== '')
        .reduce((prev, curr, _index, _arr) => {
            prev = prev;
            prev[curr.key] = prev[curr.key] || [];
            prev[curr.key].push(curr);
            return prev;
        }, {} as { [key: string]: KeyValuePair[] })

    const duplicatedKeys = Object.keys(dict).filter(key => dict[key].length > 1) ?? [];
    // const isDuplicated = duplicatedKeys.length > 0;

    duplicatedKeys.forEach(key => {
        addError(newErrors, key, '键重复')
    })

    if (Object.keys(newErrors).length > 0) {
        errors.value = newErrors;
        console.error('MetaDataEditor', '对象校验失败', newErrors);
        return;
    }

    Object.keys(model.value).forEach(k => {
        delete model.value[k]
    })

    Object.keys(dict).reduce((prev, curr) => {
        // prev = prev || {}
        const value = dict[curr][0].value ?? '';
        prev[curr] = value;
        return prev;
    }, model.value)


    errors.value = newErrors;
}, {
    deep: true
})

</script>

<template>
    <NtmKeyValuePairEditor :show-header="showHeader" v-model="keyValuePairs">
    </NtmKeyValuePairEditor>
</template>